package com.lg.concurrent.atomic;

import lombok.SneakyThrows;

import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;

/**
 * 在不改变原类型（int）的情况下
 * 可通过 AtomicIntegerFieldUpdater  使其具有原子性
 *
 * dependOn：
 *      原int   必须被 volatile 修饰
 *      原int  不能被 static 修饰
 *      原int  不能被 final 修饰
 */

public class AtomicIntegerFieldUpdaterTest{
    private static AtomicIntegerFieldUpdater<AtomicIntegerFieldUpdaterTest> update = AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdaterTest.class, "a");
    public volatile int a = 0;
    @SneakyThrows
    public static void main(String[] args){
        AtomicIntegerFieldUpdaterTest test = new AtomicIntegerFieldUpdaterTest();
        int total = 100;
        Thread[] threads = new Thread[total];
        Random random = new Random();
        for(int i=0; i<total;i++){
            threads[i] = new Thread(new Runnable() {
                @SneakyThrows
                @Override
                public void run() {
                    TimeUnit.SECONDS.sleep(random.nextInt(3));
                    update.incrementAndGet(test);
                }
            });
        }

        for (int i = 0; i < total; i++) {
            threads[i].start();
//            在这里join 是串行
//            try {
//                threads[i].join();
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }

        for (int i = 0; i < total; i++) {
            threads[i].join();
        }

        System.out.println(test.a);


    }
}